if(!window.sdk)
  window.sdk = {};
  
sdk.file=
{
	//日志
	log: function(msg) 
	{
		var logger = Components.classes["@mozilla.org/consoleservice;1"]
			                   	 .getService(Components.interfaces.nsIConsoleService);
		logger.logStringMessage("[sdk.file]-->" + msg);
	},
	
	// 获取本地文件,参数传入本地路径或file路径。返回nsILocalFile类型
	getLocalFile: function(aPath)
  {
    if(/^file/.test(aPath))
    {
      var ph = Components.classes["@mozilla.org/network/protocol;1?name=file"] 
                         .createInstance(Components.interfaces.nsIFileProtocolHandler); 
      return ph.getFileFromURLSpec(aPath).QueryInterface(Components.interfaces.nsILocalFile);
    }    
    
		var file = Components.classes['@mozilla.org/file/local;1']
				                 .createInstance(Components.interfaces.nsILocalFile);
    if(aPath)				                 
		  file.initWithPath(aPath);
		  
		return file;
	},

	// 获得特殊文件。参数module有
	// ProfD,DefProfRt,UChrm,DefRt,PrfDef,ProfDefNoLoc,APlugns,AChrom,ComsD
	// CurProcD,Home,TmpD,ProfLD,fastload,resource,Desk,Progs
	// 返回nsILocalFile类型
	getSpecialFile: function(module, subFile) 
	{
		var file = Components.classes["@mozilla.org/file/directory_service;1"]
				                 .getService(Components.interfaces.nsIProperties)
				                 .get(module, Components.interfaces.nsILocalFile);
    if(subFile)
    {
      var subs = subFile.split("/");  
      for(var i = 0; i < subs.length; i++)
      {
        file.append(subs[i]);  
      }
    }
    return file;		
	},
	
	//获取某个扩展应用的本地对象
	getExtensionsFileById: function(aId, subFile)
	{
	  if(!subFile)
	    var subFile = "";
    try
    {
      var em = Components.classes["@mozilla.org/extensions/manager;1"]
                         .getService(Components.interfaces.nsIExtensionManager);
      var file = em.getInstallLocation(aId).getItemFile(aId, subFile);
      return file.QueryInterface(Components.interfaces.nsILocalFile);
    }
    catch(e)
    {
      return null;   
    }
	},
	
	//判断文件是否存在 chrome file 绝对路径均可
	isFileExists: function(aPath)
	{
    try
    {    
      if (!/^file:/.test(aPath) && !/^chrome:/.test(aPath)) 
        aPath = this.localPathToFilePath(aPath);
      var ioService = Components.classes["@mozilla.org/network/io-service;1"]
                                .createInstance(Components.interfaces.nsIIOService);
      var channel = ioService.newChannel(aPath, null, null);
      var input = channel.open();
      return !(channel.contentLength == -1);
    }
    catch(e)
    {
      return false;
    }
  	finally
  	{
  		if(input)
  			input.close();
  	}    
	},

  //创建文件
  createFile: function(aPath)
  {
    try
    {
      var file = this.getLocalFile(aPath);
      if(file.exists())
      {
        this.log("the file is exists."); 
        return file; 
      }
      file.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0777);
      return file;  
    }
    catch(e)
    {
      this.log(e);
      return null;
    }
  },
	
  //新建文件夹
  createFolder: function(aPath)
  {
    try
    {
      var fd = this.getLocalFile(aPath);
      if(fd.exists())
      {
        this.log("the folder is exists.");
        return fd;
      }
      fd.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0777);  
      return fd;  
    }
    catch(e)
    {
      this.log(e);
      return null;
    }
  },
  
	//获取文件夹中下一级的所有文件
  getFilesByFolder: function(aFolderPath, aType, isReverse)
  {
    var fp = this.getLocalFile(aFolderPath);
    var files = fp.directoryEntries;
    var theFile;
            
    var arr = [];
    while(files.hasMoreElements())
    {
      theFile = files.getNext().QueryInterface(Components.interfaces.nsILocalFile);
      if(typeof aType == "undefined")
      {
        arr.push(theFile);   
      }
      else if(aType == "")
      {
        var isFolder = theFile.isDirectory();
        if(isFolder ^ isReverse)
        {
          arr.push(theFile);  
        }  
      }
      else
      {
        var nameArr = aType.toLowerCase().split(",");
        var fileName = theFile.leafName;
        var num = fileName.lastIndexOf(".");
        var extName = fileName.substring(num + 1,fileName.length);
        var isContain = nameArr.indexOf(extName.toLowerCase()) == -1 ? false : true;
        var isMatch = (isContain & theFile.isFile());
        if(isMatch ^ isReverse)
        {
          arr.push(theFile);  
        }
      }
    }    
    return arr;
  },	

  //复制文件         源文件  目标文件  是否覆盖    
  copyFile: function(aSource, aTarget, override)
  {
    this._copyOrMoveFile(aSource, aTarget, override, "copy");
  },
  
  //移动文件
  moveFile: function(aSource, aTarget, override)
  {
    this._copyOrMoveFile(aSource, aTarget, override, "move");   
  },
  
  _copyOrMoveFile: function(aSource, aTarget, override, aType)
  {
    var source = this.getLocalFile(aSource);
    var target = this.getLocalFile(aTarget);
    var fileName = source.leafName;    
    target.append(fileName);
    if(target.exists())
    {
      var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                              .getService(Components.interfaces.nsIPromptService);
                             
      var title = "提示";
      var text = "文件已经存在,是否覆盖?"; 
                                    
      if(override || prompts.confirm(window, title, text))
        target.remove(false);  
      else
        return false;  
    }
    if(aType == "move")
      source.moveTo(target.parent,fileName); 
    else
      source.copyTo(target.parent,fileName);  
    return true;          
  },
  
  //重命名
  renameFile: function(aPath, newName)
  {
    try
    {
      var oFile = this.getLocalFile(aPath);
      oFile.moveTo(null,newName); 
      return true; 
    }catch(e){return false;}
  },
  
  //获取扩展名
  getTypeName: function(fileName)
  {
    var str = fileName.match(/\.([^\.]*)$/);
    return str ? str[1] : "";
  },
  
  //去掉扩展名
  removeTypeName: function(fileName)
  {
    return fileName.replace(/\.[^\.]*$/,"");
  },
  
  //删除
  removeFile: function(aPath)
  {
    try
    {
      var file = this.getLocalFile(aPath);
      file.remove(true);
      return true;
    }catch(e){return false;}
  },
  
  //选择文件           文件类型 是否多个  标题    
  selectFile: function(aType, isMultiple, aTitle)
  {
    var nsIFilePicker = Components.interfaces.nsIFilePicker;
    var fp = Components.classes["@mozilla.org/filepicker;1"]
    	                 .createInstance(nsIFilePicker);
    if(!aTitle)	                 
     aTitle = "选择文件";	               
    var mode = isMultiple ? "modeOpenMultiple" : "modeOpen";  
    fp.init(window, aTitle, nsIFilePicker[mode]);
    this._initFilePickerContent(fp, aType);
    var rv = fp.show(); 
    if (rv == nsIFilePicker.returnOK) 
    {
      if(isMultiple)
      {
        var files = fp.files;
        var arr = [];
        while (files.hasMoreElements()) 
        {
          var file = files.getNext().QueryInterface(Components.interfaces.nsILocalFile);
          arr.push(file);
        }
        return arr;          
      }
      else
      {
        return fp.file;
      }
    }
    else
      return null;
  },
  
  //选择文件夹
  selectFolder: function(aTitle)
  {
    var nsIFilePicker = Components.interfaces.nsIFilePicker;
    var fp = Components.classes["@mozilla.org/filepicker;1"]
    	                 .createInstance(nsIFilePicker);
    if(!aTitle)	                 
      aTitle = "选择文件夹";	               
    fp.init(window, aTitle, nsIFilePicker.modeGetFolder);
    var rv = fp.show();
    if (rv == nsIFilePicker.returnOK) 
    {
      return fp.file;  
    }
    else 
      return null;
  },
  
  //保存文件
  openSaveDialog: function(aType, aTitle)
  {
    var nsIFilePicker = Components.interfaces.nsIFilePicker;
    var fp = Components.classes["@mozilla.org/filepicker;1"]
    	                 .createInstance(nsIFilePicker);
    if(!aTitle)	                 
      aTitle = "保存";	               
    fp.init(window, aTitle, nsIFilePicker.modeSave);
    
    this._initFilePickerContent(fp, aType);
        
    var rv = fp.show();
    if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) 
      return fp.file;  
    else 
      return null;
  },

  _initFilePickerContent: function(fp, aType, defPathObj, defName, defType)
  {
    var nsIFilePicker = Components.interfaces.nsIFilePicker;
    if(!aType)
      fp.appendFilters(nsIFilePicker.filterAll);
    else
    {  
      var typeArr = aType.split(",");
      for(var i = 0; i < typeArr.length; i++)
      {
        if(typeArr[i].toLowerCase() == "?html")
        {
          fp.appendFilters(nsIFilePicker.filterHTML);
          continue;  
        }
        else if(typeArr[i].toLowerCase() == "?text")
        {
          fp.appendFilters(nsIFilePicker.filterText);
          continue;
        }
        else if(typeArr[i].toLowerCase() == "?image")
        {
          fp.appendFilters(nsIFilePicker.filterImages);
          continue;
        }
        else if(typeArr[i].toLowerCase() == "?xml")
        {
          fp.appendFilters(nsIFilePicker.filterXML);
          continue;
        }
        else if(typeArr[i].toLowerCase() == "?xul")
        {
          fp.appendFilters(nsIFilePicker.filterXUL);
          continue;
        }
        else if(typeArr[i].toLowerCase() == "?run")
        {
          fp.appendFilters(nsIFilePicker.filterApps);
          continue;
//        if(navigator.platform.toLowerCase().indexOf("win") != -1)
//          fp.appendFilter("程序", "*.exe;*.bat");
//        else //linux
//          fp.appendFilter("程序", "*.bin;*.sh");  
//        continue;
        }                
        else if(typeArr[i].toLowerCase() == "?all")
        {
          fp.appendFilters(nsIFilePicker.filterAll);
          continue;
        }
        var extName = "*." + typeArr[i]; 
        var nType = typeArr[i].toUpperCase() + " Files(" + extName + ")";
        fp.appendFilter(nType, extName);
      }
    }
    if(defPathObj)
      fp.displayDirectory = defPathObj;
    if(defName)
      fp.defaultString = defName;
    if(defType && aType)
    {
      var idx = typeArr.indexOf(defType);
      if(idx != -1)
        fp.filterIndex = idx;       
    }
  },
  
  //是否有子节点
  hasChild: function(aPath, folderOnly)
  {
    if(!aPath)
    {
      var drvs = this.enumDrives();
      return drvs[0] ? true : false;  
    }
		try
		{
		  var fp = this.getLocalFile(aPath);
			var files = fp.directoryEntries;
			if(!folderOnly)
			  return files.hasMoreElements();
			while(files.hasMoreElements())
			{
				var theFile = files.getNext().QueryInterface(Components.interfaces.nsILocalFile);
				if(theFile.isDirectory())
				  return true;
			}
		  return false;
		}catch(e){return false}      
  },

	//读取文件,返回文件内容。
	readFile: function(aPath)
  {
		try 
		{
			var inputFile = this.getLocalFile(aPath);
			var stream = Components.classes['@mozilla.org/network/file-input-stream;1']
					                   .createInstance(Components.interfaces.nsIFileInputStream);
			stream.init(inputFile, -1, 0, 0);
			var sStream = Components.classes['@mozilla.org/scriptableinputstream;1']
					                    .createInstance(Components.interfaces.nsIScriptableInputStream);
			sStream.init(stream);
			var fileContents = sStream.read(sStream.available());
			sStream.close();
			stream.close();
			return fileContents;
		} catch (e) {
			this.log(e);
			return null;
		}
	},
	
	//读取UTF8文件
	readUTF8File: function(aPath)
	{
    var txt = this.readFile(aPath);
    txt = this.convertToUnicode(txt);
    return txt;	  
	},
 	
	//写文件
	writeFile: function(filepath, data, override)
  {
    try
    {
  		var outputFile = this.getLocalFile(filepath);
			var parentFile = outputFile.parent;
			if(!parentFile.exists())
			  this.createFolder(parentFile.path);  		
  		var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
  				                     .createInstance(Components.interfaces.nsIFileOutputStream);
  				               //覆盖   在后面添加     
      var val = override ? 0x20 : 0x10;
  		foStream.init(outputFile, 0x02 | 0x08 | val, 0666, 0); 
  		foStream.write(data, data.length); 
  		foStream.close();
  	}
  	catch(e)
  	{
  	  this.log(e);
  	}
	},
	
	//写utf-8文件
	writeUTF8File: function(filepath, data, override)
	{
	  var string = this.convertFromUnicode(data);
	  this.writeFile(filepath, string, override);
	},
	
	//转换编码格式,通常用于读文件
	convertToUnicode: function(aStr, aCharset) 
	{
		try 
		{
			var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
					                      .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
			converter.charset = aCharset ? aCharset : "UTF-8";
			var content = converter.ConvertToUnicode(aStr);

			return content;
		} catch (e) {
			this.log(e);
			return null;
		}
	},

	//转换编码格式(from)通常用于写文件
	convertFromUnicode: function(aStr, aCharset)
  {
		try 
		{
			var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
					                      .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
			converter.charset = aCharset ? aCharset : "UTF-8";
			var content = converter.ConvertFromUnicode(aStr);
			return content;
		} catch (e) {
			this.log(e);
			return null;
		}
	},

  //file路径转本地路径
  filePathToLocalPath: function(aPath) 
  { 
    if (!aPath || !/^file:/.test(aPath)) 
    {
      this.log("path error!")
      return null; 
    }
    var rv; 
    var ph = Components.classes["@mozilla.org/network/protocol;1?name=file"] 
                       .createInstance(Components.interfaces.nsIFileProtocolHandler); 
    rv = ph.getFileFromURLSpec(aPath).path; 
    return rv; 
  },
  
  //本地路径转file路径
  localPathToFilePath: function(aPath)
  {
//    var re = /(\\)/g;
//    var filePath = aPath.replace(re,"/");
//    return "file:///" + filePath;    
    var theFile = this.getLocalFile(aPath);
    var ph = Components.classes["@mozilla.org/network/protocol;1?name=file"] 
                       .createInstance(Components.interfaces.nsIFileProtocolHandler); 
    var fp = decodeURI(ph.getURLSpecFromFile(theFile));
    return fp;                         
  }, 
  
  //打开文件
  openFile: function(aPath, arg)
  {
    var threadMngr = Components.classes["@mozilla.org/thread-manager;1"]
                               .getService(Components.interfaces.nsIThreadManager);
    var self = this;                               
    //如果不用线程 有时候会卡死
    var backgroundTask = 
    {
      run : function()
      {
        try
        {
          var file = self.getLocalFile(aPath);
          if(file.isDirectory())
          {
            file.launch();
            return;  
          }
          var process = Components.classes["@mozilla.org/process/util;1"]
                                  .createInstance(Components.interfaces.nsIProcess);
          process.init(file);
          var args;
          if(arg)
            args = arg.split(" ");
          else
            args = [];  
          process.run(false, args, args.length);        
        }catch(e){}
      }
    }    
    var thread = threadMngr.newThread(0);
    thread.dispatch(backgroundTask, thread.DISPATCH_NORMAL);
  }
}

